<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="报告编码" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入报告编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="报告名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入报告名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
    
      <el-form-item label="上传季度" prop="session">
        <el-select
          v-model="queryParams.session"
          placeholder="机构等级"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in dict.type.report_sc_jd"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
          </el-select> 
      </el-form-item>
    
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:report:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:report:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:report:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:report:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="reportList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="id" />
      <el-table-column label="报告编码" align="center" prop="code" />
      <el-table-column label="报告名称" align="center">
        <template slot-scope="scope">
            <span class="downloadFun" @click="downloadFun(scope.row)">{{scope.row.name}}</span>
        </template>
      </el-table-column>
      <el-table-column label="所属部门" align="center" prop="deptName" />
      <el-table-column label="所属机构" align="center" prop="institutionName" />
      <el-table-column label="上传人" align="center" prop="createUserName" />
      <el-table-column label="上传时间" align="center" prop="createTime" />
      <el-table-column label="上传季度" align="center" prop="jdName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:report:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:report:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改【检测报告】对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="报告编码" prop="code">
          <el-input v-model="form.code" placeholder="请输入报告编码" />
        </el-form-item>
        <el-form-item label="报告名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入报告名称" />
        </el-form-item>
        <el-form-item label="所属部门" prop="deptId">
          <treeselect v-model="form.deptId" :options="deptOptions" :show-count="true" placeholder="请选择归属部门" />
        </el-form-item>
        <el-form-item label="所属机构" prop="institutionId">
          <el-select v-model="form.institutionId"  placeholder="请选择机构" style="width: 370px">
                <el-option
                  v-for="item in institutionOptions"
                  :key="item.id"
                  :label="item.name + '(机构编码:'+ item.code+')'"
                  :value="item.id"
                  :disabled="item.status != '0'"
                ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上传季度" prop="session">
          <el-select v-model="form.session" placeholder="请选择季度" style="width: 370px">
                <el-option
                  v-for="dict in dict.type.report_sc_jd"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
        </el-form-item>
        <el-form-item label="报告"
                      prop="reportUrl">
          <el-upload ref="upload"
                     :limit="1"
                     drag
                     class="avatar-uploader uploadMt"
                     :show-file-list="false"
                     action="#"
                     :multiple="false"
                     :http-request="updatereportUrl">
            <i v-if="form.reportUrl">检测报告</i>
            <i v-else
               class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listReport, getReport, delReport, addReport, updateReport } from "@/api/system/report";
import { listInstitution} from "@/api/system/institution";
import { uploadAvatar } from "@/api/system/user";
import { treeselect } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Report",
  dicts: ['report_sc_jd'],
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      reportList: [],
      // 部门树选项
      deptOptions: undefined,
      institutionOptions:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        code: null,
        name: null,
        deptId: null,
        institutionId: null,
        userId: null,
        session: null,
        reportUrl: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        institutionId: [
          { required: true, message: "所属机构不能为空", trigger: "blur" }
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getTreeselect();
  },
  methods: {
     //下载文件
    downloadFun (url) {
      let image = new Image()  //创建图片对象
      image.setAttribute('crossOrigin', 'anonymous') //设置允许跨域
      image.src = url.reportUrl //赋值src
      image.onload = () => {
        //等待图片加载完成创建canvas
        let canvas = document.createElement('canvas')
        //将图片绘制到canvas画布上
        canvas.width = image.width
        canvas.height = image.height
        let ctx = canvas.getContext('2d')
        ctx.drawImage(image, 0, 0, image.width, image.height)
        //获取图片文件格式  jpg/jpeg/png
        let ext = image.src.substring(image.src.lastIndexOf('.')+1).toLowerCase()
        //导出画布快照  此时已越过跨域限制成功取到图片数据
        let dataURL = canvas.toDataURL('image/' + ext)
        //创建a标签
        const a = document.createElement("a");
        // 赋值a标签download属性值，标明该a标签提供下载功能，同时该属性指定了下载时的文件名称
        a.download = url.name;
        //赋值a标签下载地址，即canvas导出的画布快照 base64格式的图片地址
        a.href = dataURL;
        //添加a标签到dom中
        document.body.appendChild(a);
        //触发a标签点击事件 触发下载
        a.click();
        //下载完成 删除多余的a标签  保持页面原有元素不动
        document.removeChild(a);
      }
    },
   // 上传报告
    updatereportUrl(params, type) {
      let file = params.file
      let vm = this;
      const formdata = new FormData();
      formdata.append("avatarfile", file);
      uploadAvatar(formdata).then(response => {
        this.form.reportUrl = response.imgUrl;
        
      });
    },
    /** 查询【请填写功能名称】列表 */
    getList() {
      this.loading = true;
      listReport(this.queryParams).then(response => {
        this.reportList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        this.deptOptions = response.data;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        code: null,
        name: null,
        deptId: null,
        institutionId: null,
        userId: null,
        session: null,
        createTime: null,
        updateTime: null,
        reportUrl: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "上传检测报告";
      listInstitution({pageNum: 1,pageSize: 100}).then(response => {
        this.institutionOptions = response.rows;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getReport(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改检测报告";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateReport(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addReport(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除【检测报告】编号为"' + ids + '"的数据项？').then(function() {
        return delReport(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/report/export', {
        ...this.queryParams
      }, `report_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style>
    .uploadMt .el-upload-dragger {
        width: 200px;
        height: 200px;
        display: -webkit-box;
        display: -ms-flexbox;
        display: flex;
        -webkit-box-align: center;
        -ms-flex-align: center;
        align-items: center;
        -webkit-box-pack: center;
        -ms-flex-pack: center;
        justify-content: center;
    }

    .el-upload-dragger img{
      width:200px;
      height:200px;
    }
    .downloadFun{
      cursor: pointer;
      color: #1890ff;
    }
</style>